import os
import json
import yaml
import requests
from dingtalkchatbot.chatbot import DingtalkChatbot


class AliyunDrive:
    def __init__(self):
        self.Phone = ""
        self.AccessToken = ""
        self.Signin_Count = ""
        self.phoneInfo = ""
        self.token = self.yaml_operate('r')
        self.WebHookURL = "https://oapi.dingtalk.com/robot/send?access_token=a99249d3b79f460d4f0596e0b42974f00820117695dfd3e31f3e762eb8f39"


    def yaml_operate(self, mode, data=None):
        """
        :param mode: r, w, r+, w+
        :param data: 写入时传入json数据
        :return:
        """
        # 本地和线上调试获取token配置文件
        try:
            file = open('conf/config.yaml', mode, encoding='utf-8')
        except:
            file = open("/data/api/aliyundrive/conf/config.yaml", mode, encoding='utf-8')
        if data is None:
            data = yaml.load(file, Loader=yaml.FullLoader)
            file.close()
            return data
        else:
            yaml.dump(data, file)


    def convert_size(self, size_bytes):
        # 定义存储大小单位
        units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']

        # 获取对应单位的索引
        index = 0
        while size_bytes >= 1024 and index < len(units) - 1:
            size_bytes /= 1024
            index += 1

        # 格式化输出
        return f"{size_bytes:.2f} {units[index]}"


    def getAccessToken(self, refresh_token):
        """
            获取AccessToken
        """
        global access_token
        url = "https://auth.aliyundrive.com/v2/account/token"

        headers = {
            "User-Agent": "PostmanRuntime-ApipostRuntime/1.1.0",
            "Cache-Control": "no-cache",
            "content-type": "application/json",
            "Accept": "*/*"
        }

        payload = json.dumps(
            {
                "grant_type": "refresh_token",
                "refresh_token": refresh_token
            }
        )

        try:
            result = requests.post(url=url, headers=headers, data=payload).json()
            n = 0
            for token in self.token['aliyundrive']['token']:
                if token == refresh_token:
                    self.token['aliyundrive']['token'][n] = result['refresh_token']
                n += 1
            access_token = result['access_token']
            self.Phone = result["user_name"]
            self.AccessToken = str('Bearer ' + access_token)
        except KeyError:
            data = refresh_token + "的token值错误或已过期，程序执行失败，请重新复制正确的token值"
            print(data)


    def signIn(self, refresh_token):
        url = "https://member.aliyundrive.com/v1/activity/sign_in_list"
        payload = json.dumps({"_rx-s": "mobile"})
        headers = {
            "Authorization": self.AccessToken,
            "content-type": "application/json"
        }
        try:
            response = requests.post(url=url, headers=headers, data=payload).json()
            self.Signin_Count = response['result']['signInCount']
            text = self.phoneInfo = "账号： " + self.Phone + "-签到成功, 本月累计签到" + str(self.Signin_Count) + "天"
            print(text)
        except KeyError as e:
            print(refresh_token + " 签到失败 异常: %s" % e)


    def ClaimRewards(self):
        url = "https://member.aliyundrive.com/v1/activity/sign_in_reward?_rx-s=mobile"
        result_url = "https://member.aliyundrive.com/v1/activity/sign_in_goods"
        info_url = "https://api.aliyundrive.com/v2/databox/get_personal_info"
        payload = json.dumps({"signInDay": self.Signin_Count})
        headers = {
            "Authorization": self.AccessToken,
            "content-type": "application/json"
        }
        try:
            # 领取签到福利
            response = requests.post(url=url, headers=headers, data=payload).json()

            # 获取签到内容
            result = requests.post(url=result_url, headers=headers, data=payload).json()

            # 获取云盘使用率
            getPersonalInfo = requests.post(url=info_url, headers=headers).json()
            PersonalSpaceInfo = getPersonalInfo['personal_space_info']

            # 总大小、已使用大小
            TotalSize = self.convert_size(PersonalSpaceInfo['total_size'])
            UsedSize = self.convert_size(PersonalSpaceInfo['used_size'])

            text = "#### 阿里云盘签到 \n \n>{} \n\n> 今日签到获得".format(self.phoneInfo) + result['result'][
                'rewardName'] + "\n\n" + "> 总容量：" + TotalSize + "，已使用：" + UsedSize
            self.sendDingtalk(Content=text)
            print(text + '\n' + '-' * 38)
        except KeyError as e:
            text = "领取奖励异常，请排查异常情况，异常: %s" % e
            print(text)


    def sendDingtalk(self, Content):
        DingTalk = DingtalkChatbot(webhook=self.WebHookURL)
        DingTalk.send_markdown(
            title="阿里云盘签到消息", text=Content, is_at_all=True
        )

    def run(self):
        """
            启动
        """
        for token in self.token['aliyundrive']['token']:
            while True:
                try:
                    App.getAccessToken(refresh_token=token)
                    App.signIn(refresh_token=token)
                    App.ClaimRewards()
                    break
                except Exception as e:
                    print(e)
        self.yaml_operate(mode='w', data=self.token)


if __name__ == '__main__':
    App = AliyunDrive()
    App.run()
